package org.celery.modules.other.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.celery.modules.order.service.IOrderService;
import org.celery.modules.other.service.IStatisticService;
import org.celery.modules.other.vo.StatisticUserAmountVO;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.entity.Param;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IParamService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 像素表 服务实现类
 *
 * @author Celery
 * @since 2022-04-15
 */
@AllArgsConstructor
@Service
public class StatisticServiceImpl implements IStatisticService {

    private final IParamService paramService;
    private final IOrderService orderService;
    private final IUserService userService;

    @Override
    public List<StatisticUserAmountVO> historyRankingUser(BladeUser bladeUser) {
        Param topUser = paramService.getOne(Wrappers.<Param>lambdaQuery()
                .eq(Param::getParamKey, "top_user")
        );
        int topUserInt = Func.isEmpty(topUser) ? 100 : Integer.parseInt(topUser.getParamValue());

        List<Map<String, Object>> topAmountGroupByUser = orderService.topAmountGroupByUser(topUserInt);
        if (Func.isEmpty(topAmountGroupByUser)) {
            return new ArrayList<>();
        }
        List<Long> userIdList = topAmountGroupByUser.stream().map(m -> Long.parseLong(m.get("createUser").toString())).collect(Collectors.toList());
        List<User> userList = Func.isEmpty(userIdList) ? new ArrayList<>() : userService.listByIds(userIdList);
        List<StatisticUserAmountVO> statisticUserAmountVOList = new ArrayList<>();
        for (Map<String, Object> map : topAmountGroupByUser) {
            StatisticUserAmountVO statisticUserAmountVO = new StatisticUserAmountVO();
            statisticUserAmountVO.setUserId(Long.parseLong(map.get("createUser").toString()));

            User user = userList.stream().filter(u -> Objects.equals(u.getId(), statisticUserAmountVO.getUserId())).findFirst().orElse(null);
            statisticUserAmountVO.setUserName(user == null ? "未知用户" : user.getRealName());

            statisticUserAmountVO.setSellAmount(new BigDecimal(map.get("totalAmount").toString()));
            statisticUserAmountVOList.add(statisticUserAmountVO);
        }
        return statisticUserAmountVOList;
    }
}
